<template>
  <!-- 商品菜单组件 -->
  <div class="goods">
    <!-- 菜单栏 -->
    <div class="muenBox">
      <scroll-view 
        :scroll-y="true" 
        :scroll-into-view="navId"
        :scroll-with-animation="true"
        :style="{height: clientHeight + 'px'}"
        class="muen-wrapper">
        <div class="muenList">
          <div class="muenItem" :id="'nav_' + index" @click="selectMenu(index)" :class="{active: index === currentIndex}" v-for="(item, index) in goodsData" :key="index">
            <div class="box">
              <i class="num" v-if="totalNum">{{totalNum[index]}}</i>
              <span class="icon" v-if="item.type !== -1"></span>
              <span class="name">{{item.name}}</span>
            </div>
          </div>
        </div>
      </scroll-view>
    </div>
    <!-- 商品栏 -->
    <div class="goodsBox">
      <!-- :scroll-into-view="contentId"值应为某子元素id（id不能以数字开头）。设置哪个方向可滚动，则在哪个方向滚动到该元素 -->
      <!-- :scroll-with-animation = "true"在设置滚动条位置时使用动画过渡 -->
      <scroll-view 
        :scroll-y="true" 
        :scroll-into-view="contentId"
        :scroll-with-animation = "true"
        :style="{height: clientHeight + 'px'}"
        @scroll="onScroll"
        class="foods-wrapper">
        <div class="goodsList">
          <div class="goodsItem" :id="'con_' + goodsIndex" v-for="(goodsItem, goodsIndex) in goodsData" :key="goodsIndex">
            <!-- 导航标题 -->
            <div class="titleBox">
              <span class="name">{{goodsItem.name}}</span>
            </div>
            <!-- 食物区 -->
            <div class="foodsBox" @click="toDetailFn(foodsItem)" v-for="(foodsItem, foodsIndex) in goodsItem.foods" :key="foodsIndex">
              <div class="leftBox">
                <img class="image" :src="foodsItem.image" alt="">
              </div>
              <div class="rightBox">
                <span class="name">{{foodsItem.name}}</span>
                <span class="description">{{foodsItem.description}}</span>
                <div class="sellCountBox">
                  <span class="sellCount">月售{{foodsItem.sellCount}}份</span>
                  <span class="rating">好评率{{foodsItem.rating}}%</span>
                </div>
                <div class="priceBox">
                  <span>&yen;</span>
                  <span class="price">{{foodsItem.price}}</span>
                  <span class="oldPrice" v-if="foodsItem.oldPrice">&yen;{{foodsItem.oldPrice}}</span>
                </div>
              </div>
              <div class="btnBox">
                <!-- <foodsControl @emit-add='addFoodsFn' @emit-del='delFoodsFn'></foodsControl> -->
                <foodsControl :typeName="goodsItem.name" :foodsItem="foodsItem"></foodsControl>
              </div>
            </div>
          </div>
        </div>
      </scroll-view>
    </div>
  </div>
</template>

<script>
  import { mapState, mapMutations } from 'vuex'
  import foodsControl from '../../components/foodsControl'
  export default {
    data() {
      return {
        goodsData: [], // 接收商品数据
        clientHeight: 0,
        contentId: '', // 商品id scroll-into-view 值应为某子元素id（id不能以数字开头）。设置哪个方向可滚动，则在哪个方向滚动到该元素
        currentIndex: 0, // 左右联动
        navId: '', // 导航模块对应的id，用来联动内容区域
        navMuenListHeight: 0, // 导航里ul高度
        navMuenItemHeight: 0, // 每个导航高度
        goodsItemHeightArr: [], // foods内部块的高度
        scrollContentHeight: 0 // 内容区域scroll-view高度
        // classMap: ['decrease', 'special'] // 'discount', 'special', 'guarantee', 'invoice'
      }
    },
    computed: {
      ...mapState(['buyFoodsData']),
      totalNum() {
        let num = 0
        let arr = []
        for (let i = 0; i < this.buyFoodsData.length; i++) {
          for (let j = 0; j < this.goodsData.length; j++) {
            if (this.buyFoodsData[i].typeName === this.goodsData[j].name) {
              num += this.buyFoodsData[i].foodsNum
            }
          }
          arr.push(num)
        }
        return arr
      }
    },
    components: {
      foodsControl
    },
    watch: { // 监听
      goodsData() { // 数据对象是否发生变化
        // 获取模块高度，即food-list
        setTimeout(() => {
          this.getFoodHeight()
        }, 60)
      },
      currentIndex() {
        // console.log(this.currentIndex)
        if (this.scrollContentHeight < this.navMuenListHeight) {
          let h = this.currentIndex * this.navMuenItemHeight
          if (h > this.scrollContentHeight) {
            // 导航滑动
            this.navId = `nav_${this.currentIndex}`
          } else {
            this.navId = 'nav_0'
          }
        }
      }
    },
    mounted() {
      let that = this
      //  http://localhost:8080/api/goods
      wx.request({ // 请求商品数据
        url: 'http://localhost:8080/api/goods',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success (res) {
          if (res.data.errno === 0) {
            that.goodsData = res.data.data
          }
          console.log('goodsData', res.data)
        }
      })
      // 在js中获取设备可视窗口高度 <!-- swiper（tab）高度自适应 -->
      wx.getSystemInfo({
        success (res) {
          console.log('windowHeight', res.windowHeight)
          that.clientHeight = res.windowHeight - 156
        }
      })
    },
    methods: {
      ...mapMutations({foodsDetailDataFn: 'FOODSDETAIL_DATA'}),
      toDetailFn(data) { // 跳转到详情页面
        // 创建页面后 VM6624:1 navigateTo:fail page "pages/index/pages/foodsDetail/main" is not found 需要重新启动项目
        // wx.navigateTo({
        //   url: 'pages/foodsDetail/main'
        // })
        // var url = "../one/main?id=" + this.option
        // console.log(JSON.stringify(data)) // 对象转为字符串
        // let str = JSON.stringify(data)
        // console.log(JSON.parse(str))
        // let str = JSON.stringify(data)
        // let url = '../foodsDetail/main?foodsData=' + str
        this.foodsDetailDataFn(data)
        let url = '../foodsDetail/main'
        wx.navigateTo({url})
      },
      selectMenu(index) { // 菜单选择
        this.contentId = `con_${index}` // 跳转的id
        this.navId = `nav_${index}`
        this.currentIndex = index // 当前的索引值 菜单选择的颜色
      },
      getFoodHeight() { // 微信获取节点高度
        var query = wx.createSelectorQuery()
        let h = 0
        // 对应食物盒子的高度
        query.selectAll('.goodsItem').boundingClientRect((rects) => {
          // console.log(rects)
          rects.forEach((rect) => {
            h += rect.height // 节点的高度
            this.goodsItemHeightArr.push(h)
          })
          console.log(this.goodsItemHeightArr)
        })
        // 食物容器的盒子的高度
        query.select('.foods-wrapper').boundingClientRect((rect) => {
          this.scrollContentHeight = rect.height
        })
        // 菜单的盒子高度
        query.select('.muenList').boundingClientRect((rect) => {
          this.navMuenListHeight = rect.height
        })
        // 每个菜单名所在盒子的高度
        query.select('.muenItem').boundingClientRect((rect) => {
          this.navMuenItemHeight = rect.height
        }).exec()
        // console.log(this.goodsItemHeightArr, this.scrollContentHeight, this.navMuenListHeight, this.navMuenItemHeight)
      },
      onScroll(e) { // 滚动触发
        // console.log(this.goodsItemHeightArr, this.scrollContentHeight, this.navMuenListHeight, this.navMuenItemHeight)
        // [1125, 1283.5, 1414, 1753.5, 1988.5, 2241.5, 2581, 3129.5, 3872.5, __ob__: Observer] 447 486 486
        // console.log('onScroll', e.target)
        // onScroll {mp: {…}, type: "scroll", timeStamp: 41407, x: undefined, y: undefined}
        let scrollTop = e.target.scrollTop // 滑动的高度
        // console.log('scrollTop', scrollTop)
        let goodsItemHeightArrLength = this.goodsItemHeightArr.length // 右侧数组的长度
        // console.log('goodsItemHeightArrLength', goodsItemHeightArrLength)
        // 滑动到最后
        if (scrollTop >= this.goodsItemHeightArr[goodsItemHeightArrLength - 1] - this.scrollContentHeight) {
          return 0
        } else if (scrollTop > 0 && scrollTop < this.goodsItemHeightArr[0]) {
          // 第一个右侧标题
          this.currentIndex = 0
        }
        for (let i = 0; i < goodsItemHeightArrLength; i++) {
          if (scrollTop >= this.goodsItemHeightArr[i - 1] && scrollTop < this.goodsItemHeightArr[i]) {
            this.currentIndex = i
          }
        }
      },
      addFoodsFn() {

      },
      delFoodsFn() {

      }
    }
  }
</script>

<style lang="sass" scoped>
.goods
  position: fixed
  left: 0
  top: 0
  bottom: 0
  display: flex
  width: 750rpx
  .muenBox
    flex: 0 0 160rpx
    overflow: hidden
    .muenItem
      display: table // 文字水平垂直居中
      padding: 0 24rpx
      background-color: #f3f5f7
      &.active
        background-color: #fff
        .box
          .name
            font-weight: 400
      .box
        position: relative
        display: table-cell // 文字水平垂直居中
        vertical-align: middle // 文字水平垂直居中
        width: 112rpx
        height: 108rpx
        border-bottom: 1rpx solid rgba(7, 17, 27, 0.1)
        .num
          position: absolute
          top: 12rpx
          right: -24rpx
          padding: 0 12rpx
          font-size: 18rpx
          font-weight: 700
          line-height: 32rpx
          color: rgba(255, 255, 255, 1)
          border-radius: 12rpx
          background-color: rgba(240, 20, 20, 1)
          box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0, 0, 0, 0.4)
        .icon
          display: inline-block
          margin-right: 8rpx
          vertical-align: middle
          width: 24rpx
          height: 24rpx
          background: url('../../../static/images/special_3@3x.png') no-repeat
          background-size: 100% auto
        .name
          font-size: 24rpx
          font-weight: 200
          line-height: 28rpx
          color: rgba(7, 17, 27, 1)
  .goodsBox
    flex: 0 0 590rpx
    .goodsItem
      box-sizing: border-box
      .titleBox
        padding-left: 28rpx
        width: 100%
        height: 52rpx
        border-left: 2rpx solid #d9dde1
        background-color: #f3f5f7
        .name
          font-size: 24rpx
          line-height: 52rpx
          color: rgba(147, 153, 159, 1)
      .foodsBox
        position: relative
        display: flex
        margin: 0 36rpx
        padding: 36rpx 0
        border-bottom: 1rpx solid rgba(7, 17, 27, 0.1)
        .leftBox
          flex: 0 0 128rpx
          .image
            width: 128rpx
            height: 128rpx
            border-radius: 4rpx
        .rightBox
          margin-left: 20rpx
          font-size: 0
          .name
            display: block
            margin-top: 4rpx
            font-size: 28rpx
            line-height: 28rpx
            color: rgba(7, 17, 27, 1)
          .description
            display: block
            margin: 16rpx 0
            font-size: 20rpx
            line-height: 20rpx
            color: rgba(147, 153, 159, 1)
          .sellCountBox
            margin-bottom: 16rpx
            font-size: 20rpx
            line-height: 20rpx
            color: rgba(147, 153, 159, 1)
            .sellCount
            .rating
              display: inline-block
              margin-left: 24rpx
          .priceBox
            line-height: 48rpx
            & > span
              &:nth-of-type(1)
                display: inline-block
                margin: 4rpx 2rpx 0 0
                font-size: 20rpx
                color: rgba(240, 20, 20, 1)
                vertical-align: bottom
            .price
              vertical-align: top
              font-size: 28rpx
              font-weight: 700
              color: rgba(240, 20, 20, 1)
            .oldPrice
              display: inline-block
              margin-top: -4rpx
              margin-left: 16rpx
              vertical-align: top
              font-size: 20rpx
              font-weight: 700
              text-decoration: line-through
              color: rgba(147, 153, 159, 1)
        .btnBox
          position: absolute
          right: 0
          bottom: 40rpx
</style>
